from flask import Flask, request, jsonify
from collections import deque
import time

app = Flask(__name__)

# 初始化队列和时间戳列表
code_queue = deque(maxlen=500)
code_timestamps = deque(maxlen=500)

@app.route('/code/forward', methods=['POST'])
def handle_code_forward():
    if request.json is None:
        return jsonify({"success": False, "message": "请求体为空"}), 400

    Code = request.json.get("Code")
    if "Code" not in request.json:
        return jsonify({"success": False, "message": "请求体中缺少 Code 字段"}), 400
    if Code is None:
        return jsonify({"success": False, "message": "请求体中Code字段为空"}), 400

    # 清理过期的元素
    current_time = time.time()
    while code_timestamps and (current_time - code_timestamps[0]) > 300:  # 300 秒 = 5 分钟
        code_queue.popleft()
        code_timestamps.popleft()

    # 添加 Code 到队列，并记录当前时间
    code_queue.append(Code)
    code_timestamps.append(time.time())
   # print(f"Code added to queue: {Code}")  # 添加日志

    return jsonify({"success": True}), 200